# resourcecontroller.py
import pysage
from pysage import Actor, ActorManager
import util
import Image
from messages import *
import logging
from controllers.metadatacontroller import MetaDataAPI
from pysage import get_logger
import cStringIO as StringIO

logger = get_logger()

omanager = ActorManager.get_singleton()

class ResourceController(Actor):
    subscriptions = ['AlbumSelectedMessage', 'ReloadImageResourceMessage']
    def __init__(self):
        Actor.__init__(self)
        omanager.register_actor(MetaDataAPI(), 'mapi')
    def handle_AlbumSelectedMessage(self, msg):
        '''called when first initializing some cache for an album like: image locations, etc'''
        map(lambda x: self.load_image_resource(x, size=util.BASE_THUMB_SIZE), omanager.find('mapi').get_album_photos(msg.get_property('albumid')))
    def handle_ReloadImageResourceMessage(self, msg):
        '''called when photoviewer needs higher resolution images'''
        imageid = msg.get_property('imageid')
        size = msg.get_property('size')
        return self.load_image_resource(imageid, size)
    def load_image_resource(self, imageid, size):
        im = Image.open(omanager.find('mapi').get_photo(imageid).path)
        im.thumbnail((size.x,size.y), Image.ANTIALIAS)
        data = StringIO.StringIO()
        im.save(data, 'JPEG')
        m = ImageResourceUpdatedMessage(image = imageid, data=data.getvalue())
        omanager.queue_message_to_group(omanager.PYSAGE_MAIN_GROUP, m)
        del im
        return


